from typing import Annotated, Optional, List, Dict
from fastapi import Depends, FastAPI, HTTPException, Query
from sqlmodel import Field, Session, SQLModel, create_engine, select, Relationship
from datetime import datetime


"""用户患者关系表

Keyword arguments:
UserPatientLink -- 用户患者关系表
Return: return_description
"""


class UserPatientLink(SQLModel, table=True):
    __tablename__ = "user_patient_link"  # 表名
    __table_args__ = {"comment": "用户患者关系表"}

    id: int | None = Field(default=None, primary_key=True, index=True)
    user_id: int = Field(
        nullable=False, foreign_key="user.id", ondelete="CASCADE"
    )  # 用户id
    patient_id: int = Field(
        nullable=False, foreign_key="user_patient.id", ondelete="CASCADE"
    )  # 患者id

    def __str__(self):
        return "UserPatientLink(user_id:{},patient_id:{})".format(
            self.user_id, self.patient_id
        )


"""用户表

Keyword arguments:
UserBase -- 用户基础信息表
UserCreate -- 用户创建信息表
UserUpdate -- 用户更新信息表
UserRead -- 用户读取信息表
UserModifyPassword -- 用户修改密码信息表
RespJsonUser -- 用户返回信息表
User -- 用户表
Return: return_description
"""


class UserBase(SQLModel):
    username: str | None = Field(
        max_length=50, nullable=True, unique=True)  # 用户名
    phone: str | None = Field(
        max_length=11, nullable=True, index=True, unique=True
    )  # 手机号


class UserDoctorCreate(SQLModel):
    username: str
    phone: str
    doctor: "DoctorCreate"


class UserDoctorUpdate(SQLModel):
    username: str
    phone: str
    doctor: "DoctorUpdate"


class UserPatientsCreate(SQLModel):
    username: str
    phone: str
    password: str
    # patient: "PatientCreate"


# class UserPatientsUpdate(SQLModel):
#     username: str
#     phone: str
#     password: str
    # patient: "PatientUpdate"


class UserRead(UserBase):
    id: int | None
    type: int | None  # 用户类型，1为患者，2为医生

    creator: str | None = None
    createtime: datetime | None
    updater: str | None = None
    updatetime: datetime | None

    patients: List["PatientRead"] = []
    doctor: Optional["DoctorRead"] = None


class UserModifyPassword(SQLModel):
    id: int | None
    password: str  # 密码


class RespJsonRegisterUser(SQLModel):
    code: int = Field(default=200)
    msg: str = Field(default="查询成功")
    data: List[UserRead] = []


class User(UserBase, table=True):
    __tablename__ = "user"  # 表名
    __table_args__ = {"comment": "用户表，存储注册用户信息"}

    id: int | None = Field(default=None, primary_key=True, index=True)
    type: int | None = Field(nullable=True, default=None)  # 用户类型，1为患者，2为医生
    password: str = Field(max_length=255, nullable=False)  # 密码

    create_id: int = Field(
        nullable=True, foreign_key="system_user.id", ondelete="SET NULL"
    )  # 创建人
    createtime: datetime = Field(default_factory=datetime.now)  # 创建时间
    update_id: int = Field(
        nullable=True, foreign_key="system_user.id", ondelete="SET NULL"
    )  # 更新人
    updatetime: datetime = Field(default_factory=datetime.now)  # 更新时间

    patients: Optional[List["Patient"]] = Relationship(
        back_populates="users", link_model=UserPatientLink
    )
    doctor: Optional["Doctor"] = Relationship(back_populates="user")

    def update(self):
        self.updatetime = datetime.now()

    def __str__(self):
        return "User(name:{})".format(self.username)


"""医生表

Keyword arguments:
DoctorBase -- 医生基础信息表
DoctorCreate -- 医生创建信息表
DoctorUpdate -- 医生更新信息表
DoctorRead -- 医生读取信息表
Doctor -- 医生表
Return: return_description
"""


class DoctorBase(SQLModel):
    name: str = Field(max_length=50, nullable=False)  # 医生名称
    job_num: str = Field(max_length=20, index=True, unique=True)  # 工号
    phone: str = Field(max_length=11, nullable=False)  # 手机号
    title: int = Field(nullable=False)  # 职称
    department: int = Field(nullable=False)  # 科室
    org_id: int = Field(
        nullable=False, foreign_key="system_org.id", ondelete="CASCADE"
    )  # 所属组织机构id
    is_active: bool = Field(default=True, nullable=False)  # 状态


class DoctorCreate(DoctorBase):
    pass


class DoctorUpdate(DoctorBase):
    pass


class DoctorRead(DoctorBase):
    id: int | None


class RespJsonDoctor(SQLModel):
    code: int = Field(default=200)
    msg: str = Field(default="查询成功")
    data: List[DoctorRead] = []


class Doctor(DoctorBase, table=True):
    __tablename__ = "user_doctor"  # 表名
    __table_args__ = {"comment": "用户表，存储医生账号信息"}

    id: int | None = Field(default=None, primary_key=True, index=True)
    user_id: int | None = Field(
        nullable=True, foreign_key="user.id", ondelete="SET NULL"
    )  # 关联注册用户id

    user: "User" = Relationship(back_populates="doctor")

    def update(self):
        self.updatetime = datetime.now()

    def __str__(self):
        return "Doctor(name:{})".format(self.name)


"""患者表

Keyword arguments:
PatientBase -- 患者基础信息表
PatientCreate -- 患者创建信息表
PatientUpdate -- 患者更新信息表
PatientRead -- 患者读取信息表
Patient -- 患者表
RespJsonPatient -- 患者响应json
Return: return_description
"""


class PatientBase(SQLModel):
    name: str = Field(max_length=50, nullable=False,default="张三")  # 姓名
    sex: int = Field(nullable=False,default=1)  # 性别
    birthday: datetime = Field(nullable=False,default=datetime.now().date())  # 出生日期
    id_card: str = Field(
        max_length=18, nullable=False, index=True,  unique=True, default="123456789012345678")  # 身份证号
    outpatient_num: str | None = Field(
        max_length=20, nullable=True, unique=True, default=None
    )  # 门诊号
    inpatient_num: str | None = Field(
        max_length=20, nullable=True, unique=True, default=None
    )  # 住院号
    medical_record_num: str | None = Field(
        max_length=20, nullable=True, unique=True, default=None
    )  # 病历号
    phone: str  = Field(max_length=11, nullable=False,
                       index=True, unique=True, default="12345678901")  # 手机号


class PatientCreate(PatientBase):
    pass


class PatientUpdate(PatientBase):
    pass


class PatientRead(PatientBase):
    id: int | None


class Patient(PatientBase, table=True):
    __tablename__ = "user_patient"  # 表名
    __table_args__ = {"comment": "用户表，存储患者账号信息"}

    id: int = Field(default=None, primary_key=True, index=True)

    create_id: int = Field(
        nullable=True, foreign_key="user.id", ondelete="SET NULL"
    )  # 创建人
    createtime: datetime = Field(default_factory=datetime.now)  # 创建时间
    update_id: int = Field(
        nullable=True, foreign_key="user.id", ondelete="SET NULL"
    )  # 更新人
    updatetime: datetime = Field(default_factory=datetime.now)  # 更新时间


    users: List["User"] | None = Relationship(
        back_populates="patients", link_model=UserPatientLink
    )
    

    def __str__(self):
        return "Patient(name:{})".format(self.name)


class RespJsonPatients(SQLModel):
    code: int = Field(default=201)
    msg: str = Field(default="新增成功")
    data: List[PatientRead] = []
